﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using Pifagor.IG;
using Pifagor.Runtime;
using Pifagor.Exceptions;

namespace Pifagor
{
	public class Interpreter
	{
		#region Fields
		Dictionary<string, IGFile> _loadedFunctions;
		IGFile _mainFunction;
		#endregion

		#region Public methods
		public Interpreter()
		{
			_loadedFunctions = new Dictionary<string, IGFile>();
		}

		public void AddIGFunctionFile(string IGFileName, string functionName, bool asMainFunction = false)
		{
			var ig = PifagorHelper.LoadIG(IGFileName);
			_loadedFunctions.Add(functionName, ig);

			if (asMainFunction)
			{
				if (_mainFunction != null)
					throw new ArgumentException("Main function must be set once");
				_mainFunction = ig;
			}
		}

		public Value Run()
		{
			if (_mainFunction.RootNodes.Length != 1)
				throw new RuntimeException("There must be only one root node for function");

			var rootNode = _mainFunction.Nodes[_mainFunction.RootNodes[0].Id];

			var currentContext = new ExecutionContext
			{
				IG = _mainFunction,
				Interpreter = this
			};

			return ComputableFactory.CreateComputable(currentContext, rootNode).Compute();
		}
		#endregion

		#region Internal members
		internal IGFile GetIG4Function(string functionName)
		{			
			return _loadedFunctions[functionName];
		}
		#endregion
	}
}
